<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/4/2
 * Time: 14:42
 */

namespace App\Http\Controllers\Api\Open;


use App\Http\Resources\CategoryCollection;
use App\Http\Resources\DocCollection;
use App\Http\Resources\TagCollection;
use App\Models\Category;
use App\Models\Doc;
use App\Models\DocPage;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class DocsController extends BaseController
{

    public function index(Request $request)
    {
        $user = $this->getUser();
        $doc = Doc::query()->where('user_id', $user->id);
        $doc->orderByDesc('created_at');
        $doc->with([
            'category',
            'tags',
            'pages',
            'last_update',
            'subscribers'
        ]);
        $page = $doc->withAnyStatus()->paginate(10);
        $data['docs'] = DocCollection::make($page)->hide(['buy_info']);
        return $this->success($data);
    }


    /**
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function before_edit()
    {
        $user = $this->getUser();
        $id = $this->getId('id', false);
        if ($id > 0) {
            $old = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($id);
            $data['doc'] = \App\Http\Resources\Doc::make($old)->type('edit');
            $data['tag_list'] = TagCollection::make($old->tags);
        }
        $data['category'] = \Cache::remember('web_edit_category_list', 0, function () {
            $category = Category::with('children')->where('parent_id', 0)->orderByDesc('order')->get();
            return CategoryCollection::make($category);
        });


        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function edit_base(Request $request)
    {
        $data = $request->all();
        $user = $this->getUser();
        $id = $request->input("id", false);
        if ($id) {
            $id = hashid_decode($id);
            if ($id <= 0) {
                return $this->failed('id error');
            }
        }

        $validator = \Validator::make($data, [
            'title' => 'required|max:30',
            'versions' => 'required',
            'abstract' => 'required|min:20|max:400',
            'cover' => 'required',
            'cover_id' => 'required',
            'doc_type' => ['required', Rule::in([0, 1])],
            'money' => 'numeric',
            'resell_percent' => 'integer',
            'resell_enabled' => 'required|boolean',
            'category' => 'array',
            'tags' => 'array',
            'nav_color' => 'required',
            'font_color' => 'required|boolean',
        ], [
            'abstract.min' => '描述最少20个字',
            'abstract.max' => '描述最多400个字',
            'resell_percent.max' => '分销比率最大不能超过50',
            'resell_percent.min' => '分销比率最小不能低于1',
        ]);
        $validator->sometimes(['money'], 'min:0.01', function ($input) {
            return $input->doc_type == 1;
        });
        $validator->sometimes(['resell_percent'], 'min:1|max:50', function ($input) {
            return $input->resell_enabled == true;
        });
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $cover_id = $this->getId('cover_id',false);
        $category = $request->input("category");
        $tags = $request->input("tags");
        $edit_data['title'] = $request->input("title");
        $edit_data['versions'] = $request->input("versions");
        $edit_data['abstract'] = $request->input("abstract");
        $edit_data['cover'] = $request->input("cover");
        $edit_data['cover_id'] = $cover_id;
        $edit_data['doc_type'] = $request->input("doc_type");
        $edit_data['money'] = $request->input("money");
        $edit_data['resell_percent'] = $request->input("resell_percent",0);
        $edit_data['resell_enabled'] = $request->input("resell_enabled",0);
        $edit_data['user_id'] = $user->id;
        $edit_data['nav_color'] = $request->input("nav_color");
        $edit_data['font_color'] = $request->input("font_color");
        $edit_data['category_id'] = last($category);
        if ($id > 0) {
            $doc = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($id);
            $doc->update($edit_data);
        } else {
            $edit_data['approved'] = config('approved_default', 0);
            $doc = Doc::query()->create($edit_data);
        }
        $tags_ids = collect($tags)->map(function ($item) {
            return hashid_decode($item);
        });
        $doc->tags()->sync($tags_ids);

        return $this->message('保存成功');
    }

    /**
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function edit_book()
    {
        $id = $this->getId();
        $user = $this->getUser();
        $doc = Doc::query()->withAnyStatus()->where('user_id', $user->id)->findOrFail($id);
        $data['doc'] = \App\Http\Resources\Doc::make($doc);
        $pages = DocPage::getAllPage($doc);
        $data['pages'] = $pages;
        /*$pages = $doc->pages()->with(['children'])->where("parent_id", 0)->orderByDesc('order')->get();
        $data['pages'] = DocPageCollection::make($pages);*/
        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function add_page(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'title' => 'required|max:30',
            'doc_id' => 'required',
            'is_try' => 'required|boolean',
            'is_group' => 'required|boolean',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $doc_id = $this->getId('doc_id');
        $parent_id = $this->getId('parent_id', false);
        $user = $this->getUser();
        $id = $this->getId('id', false);
        if ($id) {
            $doc_page = DocPage::query()->where('doc_id', $doc_id)
                ->where('user_id', $user->id)->findOrFail($id);
            $doc_page->title = $request->input("title");
            $doc_page->is_try = $request->input("is_try");
            $doc_page->is_group = $request->input("is_group");
            $doc_page->save();
        } else {
            $doc_page = DocPage::query()->create([
                'doc_id' => $doc_id,
                'title' => $request->input("title"),
                'is_try' => $request->input("is_try"),
                'is_group' => $request->input("is_group"),
                'user_id' => $user->id,
                'parent_id' => $parent_id,
                'order' => DocPage::getOrder($parent_id, $doc_id)
            ]);
        }
        return $this->success(\App\Http\Resources\DocPage::make($doc_page));
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function save_content(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'content' => 'required',
            'doc_id' => 'required',
            'id' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $id = $this->getId();
        $doc_id = $this->getId('doc_id');
        $user = $this->getUser();
        $page = DocPage::query()->where('user_id', $user->id)->findOrFail($id);
        $page->content = $request->input("content");
        $page->model = 'md';
        $page->save();

        return $this->message("保存成功");

    }

    /**
     * @throws \App\Exceptions\ApiException
     */
    public function get_page()
    {
        $id = $this->getId();
        $user = $this->getUser();
        $page = DocPage::query()->where('user_id', $user->id)->findOrFail($id);

        return $this->success(\App\Http\Resources\DocPage::make($page)->type('open'));
    }


    /**
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function delete_page()
    {
        $id = $this->getId();
        $doc_id = $this->getId('doc_id');
        $user = $this->getUser();
        $page = DocPage::query()->where('user_id', $user->id)->findOrFail($id);
        $children_ids = DocPage::getPageChildrenIds($page);
        $delete_ids = array_collapse([[$id], $children_ids]);

        $del_count = DocPage::deletedByIds($user, $delete_ids);
        return $this->message('本次共删除' . $del_count . '个章节');
    }

    public function collectUrl(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'url' => 'required|url',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $json = $request->input("json", false);
        $url = $request->input("url");

        $http = new \GuzzleHttp\Client();
        $op = [];
        if ($json) {
            $op['headers'] = [
                'Accept' => 'application/json',
                'X-Requested-With' => 'XMLHttpRequest',
            ];
        }

        $res = $http->request('GET', $url, $op);
        return $this->success($res->getBody()->getContents());

    }

}